package heap;

import ArrayList.Array;

public class MaxHeap<E extends Comparable<E>> {
    private Array<E> data;

    public MaxHeap() {
        data = new Array<>();
    }

    public MaxHeap(E[] arr) {
        data = new Array<>(arr);
        for (int i = parent(arr.length - 1); i >= 0; i--) {
            sitfDown(i);
        }

    }

    public MaxHeap(int capacity) {
        data = new Array<>(capacity);
    }

    public int getSize() {
        return data.getSize();
    }

    public boolean isEmpty() {
        return data.getSize() == 0;
    }

    public int parent(int index) {
        if (index == 0) {
            throw new IllegalArgumentException("index-0  no parent");
        }
        return (index - 1) / 2;
    }

    public int leftChild(int index) {
        return index * 2 + 1;
    }

    public int rightChild(int index) {
        return index * 2 + 2;
    }

    public E get(int index) {
        return data.get(index);
    }

    //添加元素
    public void add(E e) {
        if (getSize() == 0) {
            data.addLast(e);
            return;
        }
        data.addLast(e);
        sitfUp(getSize() - 1);

    }

    private void sitfUp(int k) {

        while (k > 0 && get(k).compareTo(get(parent(k))) > 0) {
            data.swap(k, parent(k));
            k = parent(k);
        }
    }

    //删除最大元素
    public E extractMax() {
        if (getSize() == 0) {
            throw new IllegalArgumentException("heap is empty");
        }
        E res = data.getFirst();
        data.swap(0, getSize() - 1);
        data.removeLast();
        sitfDown(0);
        return res;

    }

    private void sitfDown(int k) {

        while (leftChild(k) < getSize()) {
            int j = leftChild(k);
            if (j + 1 < getSize() && get(j).compareTo(get(j + 1)) < 0) {
                j = rightChild(k);
            }

            if (get(k).compareTo(get(j)) >= 0) {
                break;
            }

            data.swap(k, j);
            k = j;


        }
    }

    //将堆得最大值替换
    public E replace(E e) {
        E res = data.getFirst();
        data.set(0, e);
        sitfDown(0);
        return res;
    }

    //遍历
    public void traverse() {
        for (int i = 0; i < getSize(); i++) {
            System.out.print(data.get(i) + " ");
        }
    }


}
